package com.lagou;

import com.alibaba.fastjson.JSONObject;
import com.lagou.handler.UserServerHandler;
import com.lagou.service.UserServiceImpl;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class ServerBootstrap {

    public static void main(String[] args) throws InterruptedException {

        SpringApplication.run(ServerBootstrap.class, args);
        UserServiceImpl.startServer("127.0.0.1",8991);

        new Thread(()->{

            while (true) {
                try {
                    Thread.sleep(1000);
                    ZkClient zkClient = new ZkClient("127.0.0.1:2181", 5000);
                    Object o = zkClient.readData(UserServerHandler.servrName);

                    if(o!=null){
                        String jsonStr = o.toString();
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        Long responseTime = Long.valueOf(jsonObject.get("responseTime").toString());
                        //超过5s清零
                        if (System.currentTimeMillis()-responseTime>5000) {

                            jsonObject.put("runTime",0);
                            String str = jsonObject.toJSONString();
                            zkClient.writeData(UserServerHandler.servrName,str);
                            System.out.println("超过5s清零");
                        }
                    }
                    zkClient.close();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }


}
